package com.web.bdo.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;

import com.web.bdo.User;
import com.web.bdo.dao.util.UserDaoUtil;
import com.web.util.sql.DatabaseConnector;
import com.web.util.sql.IdGenerator;
import com.web.util.string.StringUtil;

public class UserDao {	

	public ActionErrors add(User user) {
		
		ActionErrors errors = new ActionErrors();
		PreparedStatement pStat = null;		
		String sql = Messages.getString("UserDao.sql.insert"); //$NON-NLS-1$
		
		if (!UserDaoUtil.isAvailable(user.getEmailAddress())) {
			errors.add("emailAddress", new ActionMessage("errors.signup.emailAlreadyRegistered")); //$NON-NLS-1$ //$NON-NLS-2$
			return errors;
		}
		
		try {
			pStat = DatabaseConnector.getConnection().prepareStatement(sql);
			pStat.setString(1, IdGenerator.getId(Messages.getString("UserDao.users.prefix"), Messages.getString("UserDao.users.tableName"), 1000)); //$NON-NLS-1$ //$NON-NLS-2$
			pStat.setString(2, user.getEmailAddress());
			pStat.setString(3, user.getPassword());
			pStat.setString(4, StringUtil.formalizeCase(user.getFirstName()));
			pStat.setString(5, StringUtil.formalizeCase(user.getLastName()));
			pStat.setInt(6, user.getSex()-1);
			pStat.setInt(7, user.getAge());
			pStat.setString(8, user.getCountry());
			pStat.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			errors.add("userDatabase", new ActionMessage("errors.signup.sql.add")); //$NON-NLS-1$ //$NON-NLS-2$
		}		
		return errors;
	}
	
	public ActionErrors update(User user) {
		
		ActionErrors errors = new ActionErrors();
		PreparedStatement pStat = null;		
		String sql = Messages.getString("UserDao.sql.update"); //$NON-NLS-1$
		
		try {
			pStat = DatabaseConnector.getConnection().prepareStatement(sql);
			pStat.setString(1, user.getId()); //$NON-NLS-1$ //$NON-NLS-2$
			pStat.setString(2, user.getEmailAddress());
			pStat.setString(3, user.getPassword());
			pStat.setString(4, StringUtil.formalizeCase(user.getFirstName()));
			pStat.setString(5, StringUtil.formalizeCase(user.getLastName()));
			pStat.setInt(6, user.getSex() - 1);
			pStat.setInt(7, user.getAge());
			pStat.setString(8, user.getCountry());
			pStat.setString(9, user.getId());
			pStat.executeUpdate();
			UserDaoUtil.reload(user);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			errors.add("userDatabase", new ActionMessage("errors.signup.sql.update")); //$NON-NLS-1$ //$NON-NLS-2$
		}		
		return errors;
	}
	
	
	
	
}
